import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Tabs, List, Button, SearchBar, Icon, Toast, ActivityIndicator, Tools } from 'weaver-mobile';
import { Form, CKRichText, ListViewPage, SearchAdvanced, RouteLayout } from 'weaver-mobile-page';
import { toJS } from 'mobx';
const getLabel = Tools.getLabel;

const tabsData = [
  { title: getLabel('131684', '发广播') },
  { title: getLabel('510038', '发送记录') }

]
const config = { // 富文本配置
  startupFocus:false
};

@inject('smsRadioStore')
@withRouter
@observer
export default class SmsRadio extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchVal: '',
    }
  }

  componentDidMount() {
    const { smsRadioStore } = this.props;
    const { getSendBroadcastCondition, getData, getRecordAdvanceCondition, ckRichTextStore } = smsRadioStore;

    getSendBroadcastCondition();
    getData({ url: '/api/msgcenter/broadcast/mobile/queryBroadcastRecord', method: 'post' });
    getRecordAdvanceCondition();
  }
  // //表单重置
  // handleReset = () => {
  //   const { smsRadioStore } = this.props;
  //   const { form, ckRichTextStore } = smsRadioStore;
  //   form.resetFields();
  //   ckRichTextStore.setData((e) => {
  //     console.log(e)
  //   })
  // }
  //表单提交
  handleSubmit = () => {
    const { smsRadioStore } = this.props;
    const { form, submitBroadcast, ckRichTextStore } = smsRadioStore;
    const result = form.doValidate();

    let receivertype = form.formParams.receivertype
    let receiver = form.formParams.receiver
    let title = form.formParams.title
    if (result.pass) {
      if (ckRichTextStore.getData().richText && ((receivertype == '1' && receiver) || receivertype == '0')) {
        if (title.length < 100) {
          submitBroadcast(form.formParams).then(() => {
            this.props.history.go(0)
          });
          Toast.success(getLabel('516179', '发送成功！'), 1);
        } else {
          Toast.fail(getLabel('517205', '广播标题长度过高，不要超过100个字符'), 1);
        }
      } else {
        Toast.fail(getLabel('516180', '广播内容或必填项未填写！'), 1);
      }
    }
  }

  getFields = () => {
    const { smsRadioStore } = this.props;
    const { form, formConditions, ckRichTextStore, getSendBroadcastCondition } = smsRadioStore;
    const { isInit } = form;
    const fields = [];

    if (isInit) {
      toJS(formConditions[0].items).forEach((field) => {
        fields.push(<Form.Item
          key={field.domkey.join('__')}
          form={form}
          fieldConfig={field}
          onChange={(field, val) => {
            form.onChange(field, val);
            if (field.domkey[0] === 'type') {
              // ckRichTextStore.richEditorStore.setData(content)
              let titleVal = form.formParams.title;
              let content = ckRichTextStore.getData().richText;
              if (val[0]) {
                getSendBroadcastCondition(val[0].id).then(() => {
                  //form.updateFields({ type: { value: val},title: { value: 99 }})
                  form.updateFields({ type: { value: val }, title: { value: titleVal } })
                  ckRichTextStore.richEditorStore.setData(content)
                });
              }
            }
          }}
        />);
      });
    }
    return fields;
  }

  //广播记录高级搜索点击重置
  reset = () => {
    const { smsRadioStore } = this.props;
    const { search, listV, getData } = smsRadioStore;

    this.setState({ searchVal: '' })
    search.form.resetFields();
  }
  //广播记录高级搜索点击搜索
  advancedSubmit = () => {
    const { smsRadioStore } = this.props;
    const { search, listV, getData } = smsRadioStore;

    //整理高级搜索参数
    let allParams = search.form.formParams;
    //清除列表数据
    listV.clearData();
    //带参数请求列表数据
    getData({
      url: '/api/msgcenter/broadcast/mobile/queryBroadcastRecord',
      method: 'post',
      params: allParams
    });
  }

  //广播记录搜索框键盘enter回调
  searchSubmit = () => {
    const { listV, getData } = this.props.smsRadioStore;

    let titleVal = this.state.searchVal;
    //清除列表数据
    listV.clearData();
    this.props.history.go(-1)
    setTimeout(function () {
      // 带参数请求列表数据
      getData({
        url: '/api/msgcenter/broadcast/mobile/queryBroadcastRecord',
        method: 'post',
        params: { title: titleVal }
      });
    }, 500);
    // listV.updateDataSource();
  }
  searchBarFocus = () => {
    const { smsRadioStore } = this.props;
    const { searchLayout } = smsRadioStore;


    this.props.history.push(searchLayout.path);
  }
  //点击接受人数回调函数
  receiverClick = (receiverid) => {
    const { smsRadioStore } = this.props;
    const { receiverGetData, receiverListV } = smsRadioStore;

    receiverListV.clearData();
    receiverGetData({ url: '/api/msgcenter/broadcast/mobile/getBroadcastReceiverList', method: 'post', params: { receiverid: receiverid } });
    this.props.history.push(`/sms-receive/?id=${receiverid}`)

  }
  //点击重新发送回调函数
  resend = () => {
    const { smsRadioStore } = this.props;
    const { form, detailItem, setState, ckRichTextStore, workFlowReplaceData, docReplaceData, fileData, workFlowRes, docRes, fileRes, changedatas } = smsRadioStore;

    form.resetFields();
    setState({ selectKey: 0 })
    form.updateFields({ title: { value: detailItem.title } })
    // ckRichTextStore.richEditorStore.setData(detailItem.contexts)两个方法都可以修改richText
    ckRichTextStore.setData({ richText: detailItem.contexts })
    ckRichTextStore.replyStore.setAttach('workflow', workFlowReplaceData);
    ckRichTextStore.replyStore.setAttach('doc', docReplaceData);
    ckRichTextStore.replyStore.setAttach('upload', fileData);
    if (workFlowRes) {
      changedatas.signworkflowids = workFlowRes.workFlowBizids;
      changedatas.signworkflowreplacedata = workFlowRes.workFlowJson;
    }
    if (docRes) {
      changedatas.signdocids = docRes.docBizids;
      changedatas.signdocreplacedata = docRes.docJson;
    }
    if (fileRes) {
      changedatas.uploadfileids = fileRes.fileBizids;
      changedatas.uploadfiledata = fileRes.fileJson;
    }
    this.props.history.push(`/sms-radio/`)
    //this.props.history.go(-1)两个方法都可以返回上一级

  }
  //广播记录列表带点击单条记录
  onRecordClick = (id) => {
    const { smsRadioStore } = this.props;
    const { getSmsDetailById, layout } = smsRadioStore;

    getSmsDetailById(id).then(() => {
      this.props.history.push(layout.path)
    });
  }

  // 自定义渲染模板
  getTemplate = () => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          return (
            <div className="sms-radio-list-item" onClick={() => this.onRecordClick(data.ID)}>
              <div>{data.TITLE}</div>
              <div className="sms-radio-list-item-info">
                <span>{data.CREATERUSERIDspan}</span>
                <span>{data.ttime}</span>
              </div>
            </div>
          );
        },
      }],
    };
    return newTemp;
  }
  //隐藏菜单--重新发送
  getSwipeActionProps = () => ({

    right: [
      {
        text: getLabel('507765', '重新发送'),
        onPress: (data) => {
          const { smsRadioStore } = this.props;
          const { getSmsDetailById } = smsRadioStore;

          getSmsDetailById(data.ID).then(() => {
            this.resend();
          });
        },
        className: `sms-radio-list-item-resend`,
      },
    ],
  })
  //reply组件流程文档类型浏览按钮change触发事件
  onBrowserChange = (key, datas) => {
    const { smsRadioStore } = this.props;
    const { ckRichTextStore, changedatas, setState } = smsRadioStore;
    let workFlowids = '';
    let docids = '';
    if (key === 'workflow') {
      datas.map(v => {
        workFlowids += v.id + ','
      });
      workFlowids = workFlowids.substring(0, workFlowids.length - 1)
      changedatas.signworkflowids = workFlowids;
      changedatas.signworkflowreplacedata = datas;
      setState(changedatas)
    }
    if (key === 'doc') {
      datas.map(v => {
        docids += v.id + ','
      });
      docids = docids.substring(0, docids.length - 1)
      changedatas.signdocids = docids;
      changedatas.signdocreplacedata = datas;
      setState(changedatas)
    }

    // console.log(toJS(datas))
    //   if(key === 'workflow'){
    //     ckRichTextStore.insertHtml(`<span>${a}</span>&nbsp;<a href="javascript:void(0)" style="text-decoration:underline !important;" linkid="${v.id}" linktype="${key}" onclick="try{return openAppLink(this,${v.id});}catch(e){}">${v.name}</a>&nbsp;&nbsp;&nbsp;</br>`);
    //   }else if(key === 'doc'){
    //     ckRichTextStore.insertHtml(`<span>${b}</span>&nbsp;<a href="javascript:void(0)" style="text-decoration:underline !important;" linkid="${v.id}" linktype="${key}" onclick="try{return openAppLink(this,${v.id});}catch(e){}">${v.name}</a>&nbsp;&nbsp;&nbsp;</br>`);
    //   }
  }

  //reply组件附件上传后事件
  onUploadChange = (key, datas) => {
    const { smsRadioStore } = this.props;
    const { ckRichTextStore, changedatas, setState } = smsRadioStore;
    // const c = '<svg class="am-icon am-icon-enclosure-1 am-icon-xxs"><use xlink:href="#enclosure-1"></use></svg>';
    let fileids = [];
    datas.map(item => {
      fileids.push(item.fileid)
    });
    changedatas.uploadfileids = fileids;
    changedatas.uploadfiledata = datas;
    setState(changedatas)
    // let str="";
    // datas.map(item => {
    //   str = `<span>${c}</span>&nbsp;<a href='javascript:void(0)' onclick='try{opendoc1(${item.fileid},this);return false;}catch(e){}' ondblclick='return false;' unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.filename}</a>
    //   &nbsp;<a href='javascript:void(0)'  onclick='try{downloads(${item.imagefileid},this,"${item.filename}");return false;}catch(e){}' unselectable='off' target='_blank' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>下载(${item.filesize})</a></br>`;
    //   ckRichTextStore.insertHtml(str);
    // });
  }
  onImgChange = (datas) =>{
    const { smsRadioStore } = this.props;
    const { ckRichTextStore} = smsRadioStore;

    ckRichTextStore.insertHtml(`<img data-imgsrc="${datas[0].imgSrc}" src="${datas[0].imgSrc}" alt="" style="max-width: 100%;height: auto;"/>&#8203;`);
    
  }
  //渲染流程业务数据  
  renderWorkFlowBiz = () => {
    const { smsRadioStore } = this.props;
    const { workFlowBiz } = smsRadioStore;

    if (workFlowBiz) {
      return workFlowBiz.map((val, index) => {
        let valHtml = `<a contenteditable='false' onclick="window.openLink('/spa/workflow/static4mobileform/index.html#/req?requestid=${val.bizid}')"` +
          'href="javascript:void(0);" unselectable="off" contenteditable="false"' +
          'style="cursor:pointer;text-decoration:none !important;margin-right:8px">' +
          `${val.bizname}</a>&nbsp;</br>`;
        return (
          <div key={index} className={index == 0 ? "container-content-Workflow" : "container-content-Workflow-n"} dangerouslySetInnerHTML={{ __html: valHtml }}></div>
        );
      })
    }
  }
  //渲染文档业务数据  
  renderDocBiz = () => {
    const { smsRadioStore } = this.props;
    const { docBiz } = smsRadioStore;

    if (docBiz) {
      return docBiz.map((val, index) => {
        let valHtml = `<a contenteditable='false' onclick="window.openLink.openDocument(${val.bizid})"` +
          'href="javascript:void(0);" unselectable="off" contenteditable="false"' +
          'style="cursor:pointer;text-decoration:none !important;margin-right:8px">' +
          `${val.bizname}</a>&nbsp;</br>`;
        return (
          <div key={index} className={index == 0 ? "container-content-Workflow" : "container-content-Workflow-n"} dangerouslySetInnerHTML={{ __html: valHtml }}></div>
        );
      })
    }

  }
  //渲染附件业务数据  
  renderFileBiz = () => {
    const { smsRadioStore } = this.props;
    const { fileBiz } = smsRadioStore;

    if (fileBiz) {
      return fileBiz.map((val, index) => {
        let valHtml = `<a onclick="window.openLink.openDocument(${val.bizid})" unselectable="off"` +
          'style="cursor:pointer;text-decoration:none !important;margin-right:8px"' +
          `href="javascript:void(0);" contenteditable="false">${val.bizname}</a>&nbsp;<a unselectable='off' contenteditable='false'` +
          `href='javascript:try{downloadFile(\"${val.loadlink}\","${val.bizid}")}catch(e){window.open(\"${val.loadlink}\")}' ` +
          `style='cursor:pointer;text-decoration:none;margin-right:8px'>下载(${val.filesize})</a>&nbsp;</br>`;
        return (
          <div key={index} className={index == 0 ? "container-content-Workflow" : "container-content-Workflow-n"} dangerouslySetInnerHTML={{ __html: valHtml }}></div>
        );
      })
    }
  }

  //tab标签切换
  onTabChange = (tab, index) => {
    const { smsRadioStore } = this.props;
    const { setState, selectKey, ckRichTextStore,listV} = smsRadioStore;

    setState({ selectKey: index });
    listV.updateDataSource();
  }


  render() {
    const { smsRadioStore } = this.props;
    const { selectKey, setState, form, ckRichTextStore, listV, loading, search, layout, detailItem, animating, workFlowBiz, docBiz, fileBiz, searchLayout } = smsRadioStore;
    const { formParams } = form;
    const replyProps = {
      onImgChange:this.onImgChange,
      onBrowserChange: this.onBrowserChange,
      onUploadChange: this.onUploadChange,
      leftConfig: [
        { type: 'voice' },
        { type: 'blog-tupian', model: 2 },
        { type: 'tianjia' }
      ]
    }
    return (
      <div  className="sms-radio-page" >
        <Tabs
          tabs={tabsData}
          initialPage={selectKey}
          page={selectKey}
          onChange={(tab, index) => this.onTabChange(tab, index)}
          animated={false}
          useOnPan={false}
        />
        <div className="toast-example">
          <ActivityIndicator
            toast
            text="Loading..."
            animating={animating}
          />
        </div>
        <Route
          key={layout.id}
          path={layout.path}
          render={() => (
            <RouteLayout>
              <div
                key="radioDetailePage"
                className="wm-route-layout"
              >
                <div style={{ background: 'white', height: '100%', overflow: 'auto', width: '100%' }}>
                  <div className="sms-radio-dialog-container">
                    <div className="container-head">
                      <div className="container-title">{detailItem.title}</div>
                      <div className="container-info">
                        <div className="container-sendInfo">
                          <span>{detailItem.creater}</span>
                          <span className="container-time">{detailItem.createdate}  {detailItem.createtime}</span>
                        </div>
                        <div>{getLabel('515418', '接收人数：')}<a onClick={() => this.receiverClick(detailItem.receieverid)} className="column-text" >{detailItem.count}</a></div>
                      </div>
                    </div>
                    <div className="container-content" dangerouslySetInnerHTML={{ __html: detailItem.contexts }}></div>
                    <div className="container-content" style={{ display: fileBiz.length > 0 ? 'block' : 'none' }}>
                      <Icon key="enclosure-1" type="enclosure-1" size="xxs" />
                      {this.renderFileBiz()}
                    </div>
                    <div className="container-content" style={{ display: docBiz.length > 0 ? 'block' : 'none' }}>
                      <Icon key="file" type="file" size="xxs" />
                      {this.renderDocBiz()}
                    </div>
                    <div className="container-content" style={{ display: workFlowBiz.length > 0 ? 'block' : 'none' }}>
                      <Icon key="flow" type="flow" size="xxs" />
                      {this.renderWorkFlowBiz()}
                    </div>
                  </div>

                  <div style={{
                    position: 'absolute',
                    width: '100%',
                    bottom: '0px',
                    background: 'white',
                  }}>
                    <Button type="primary" onClick={this.resend}>{getLabel('507765', '重新发送')}</Button>
                  </div>
                </div>
              </div>
            </RouteLayout>
          )}
        />
        <Route
          key={searchLayout.id}
          path={searchLayout.path}
          render={() => (
            <RouteLayout>
              <div
                key="searchRadioPage"
                className="wm-route-layout"
              >
                <div style={{ background: 'white', height: '100%', overflow: 'auto', width: '100%' }}>
                  <div className="sms-radio-search-page">
                    <SearchBar
                      value={this.state.searchVal}
                      className="search-select"
                      placeholder={getLabel('500351', '请输入关键字')}
                      onChange={val => this.setState({ searchVal: val }, search.form.updateFields({ title: { value: val } }))}
                      onSubmit={this.searchSubmit}
                      ref={ref => { if (ref) { ref.focus() } }}
                    />
                  </div>
                </div>
              </div>
            </RouteLayout>
          )}
        />
        <div>
          {
            selectKey === 0 ? (
              <div style={{
                overflow: 'auto',
                height: '190px'
              }}>
                <Form>
                  <List>
                    {this.getFields()}
                  </List>
                </Form>
              </div>
            ) : (
                <div>
                  <SearchBar
                    value={this.state.searchVal}
                    className="search-select"
                    placeholder={getLabel('500351', '请输入关键字')}
                    showExtraButton
                    extraButton={[
                      { key: 'advanced', show: <Icon key="filter-o" type="filter-o" /> },
                    ]}
                    // onChange={val => this.setState({ searchVal: val }, search.form.updateFields({ title: { value: val } }))}
                    // onSubmit={this.searchSubmit}
                    onExtraButtonClick={() => this.props.history.push(search.path)}
                    onFocus={() => this.searchBarFocus()}
                  />
                  <SearchAdvanced
                    store={search}
                    onSubmit={this.advancedSubmit}
                    onReset={this.reset}
                    onChange={(condition, value) => {
                      if (condition.domkey[0] === 'title') {
                        this.setState({ searchVal: value })
                      }
                    }}
                  />
                  <ListViewPage.Normal
                    loading={loading}
                    store={listV}
                    rowKey="ID"
                    getTemplate={this.getTemplate}
                    withSwipeAction
                    swipeActionProps={this.getSwipeActionProps()}
                  />

                </div>
              )
          }
          {
            (
              <div style={{
                display: selectKey === 0 ? 'block' : 'none'
              }}>
                <div style={{
                  position: 'absolute',
                  width: '100%',
                  top: formParams.receivertype === '0' ? '190px' : '235px',
                  bottom: '47px',
                  background: 'white'
                }}>
                  <CKRichText
                    store={ckRichTextStore}
                    // placeholder={getLabel('516181', '请填写广播内容...')}
                    onChange={(e) => { ckRichTextStore.text = e }}
                    replyProps={replyProps}
                    config={config}
                  />
                </div>
                <div style={{
                  position: 'absolute',
                  width: '100%',
                  bottom: '0px',
                  background: 'white'
                }}>
                  <Button type="primary" onClick={this.handleSubmit}>{getLabel('2083', '发送')}</Button>
                </div>
              </div>
            )
          }
        </div>
      </div>
    )
  }
}